﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CSharpWin;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.APCode;
using System.Linq;
using CSharpWin_JD.CaptureImage;
using agsXMPP.protocol.client;
using System.Threading.Tasks;

namespace YanMsg.View
{
    /// <summary>
    /// Chat.xaml 的交互逻辑
    /// </summary>
    public partial class Chat : ModernWindow
    {

        public string Key = null;

        public static vw_Yan_Chat_user chatinfo = null;

        private UdpSendFile udpSendFile;



        /// <summary>
        ///
        /// </summary>
        /// <param name="userName">当前用昵称</param>
        /// <param name="netStream">发送和接受信息的网络流</param>
        public Chat(string friendNumber)
        {
            try
            {
                chatinfo = UserData.ListPeople.SingleOrDefault(D => D.UserName == friendNumber);
                InitializeComponent();

                this.Style = (Style)App.Current.Resources["EmptyWindow"];
                this.Key = friendNumber;


                Task UDPTask = new Task(UDPFileTask);
                UDPTask.Start();
                if (chatinfo.UserIPAdress == "")
                {
                    imgSendFile.IsEnabled = false;
                }
            }
            catch (Exception e)
            {

                MsgManger.Show(e.Message);
            }
         
        }

    

        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        /// <summary>
        /// 关闭前动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SendFileControl.Controls.Count > 0)
            {
                MessageBoxResult result = MessageBox.Show("有文件正在传输,确定要关闭吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                //关闭窗口
                if (result == MessageBoxResult.Yes)
                    e.Cancel = false;
                //不关闭窗口
                if (result == MessageBoxResult.No)
                    e.Cancel = true;
            }          
        }



        /// <summary>
        /// 关闭后动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowTalking_Closed(object sender, EventArgs e)
        {
            try
            {
                UserData.DictionaryChat.Remove(this.Key);
                foreach (FileTransfersItem item in SendFileControl.Controls)
                {
                    if (item.Style.ToString() == "Style")
                    {
                        SendFileManager sendFileManager =
                item.Tag as SendFileManager;
                        udpSendFile.CancelSend(sendFileManager.MD5);
                    }
                    else
                    {
                        RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
                        rse.Cancel = true;
                        FileTansfersContainer Container = item.Parent as FileTansfersContainer;
                        Container.RemoveItem(item);
                        item.Dispose();
                        UserData.udpReceiveFile.AcceptReceive(rse);
                    }
                }
            }
            catch (Exception error)
            {
                MsgManger.Show(error.Message);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            SendMsg();
        }
        private void Login_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == System.Windows.Input.Key.Enter)
            {
                SendMsg();
            } 

        }

        private void SendMsg()
        {
            try
            {
                TextRange msgBoxContent = new TextRange(this.MyMessageBox.Document.ContentStart, this.MyMessageBox.Document.ContentEnd);
                if (!msgBoxContent.IsEmpty)
                {

                    Message msg = new Message();
                    msg.Type = MessageType.chat;
                    msg.To = chatinfo.UserName.TOJid();
                    msg.Body = ZipHelper.GZipCompressString(ChatManger.toRtf(this.MyMessageBox));
                    Login.connection.Send(msg);

                    //添加到本地
                    ChatHelp.InsertChat(UserData.UserNumber, msg.To.User, msg.Body);

                    //添加信息头
                    string strMSTitle = UserData.UserRealNumber + "  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    TextBlock TB = new TextBlock(new Bold(new Run(strMSTitle)));
                    TB.Foreground = new SolidColorBrush(Colors.RoyalBlue);
                    BlockUIContainer BU = new BlockUIContainer(TB);
                    this.ViewMessgeBox.Document.Blocks.Add(BU);

                    //添加信息内容
                    List<Block> ListMsgBlock = new List<Block>();
                    for (int i = this.MyMessageBox.Document.Blocks.Count - 1; i >= 0; i--)
                    {
                        Block q = this.MyMessageBox.Document.Blocks.ElementAt(i);
                        ListMsgBlock.Add(q);
                    }
                    ListMsgBlock.Reverse();
                    this.ViewMessgeBox.Document.Blocks.AddRange(ListMsgBlock);
                    //添加信息内容

                    this.ViewMessgeBox.ScrollToEnd();
                    this.MyMessageBox.Document.Blocks.Clear();
                }
            }
            catch (Exception e)
            {

                MsgManger.Show(e.Message);
            }
        
       
        }


        //聊天记录
        private void imgChatHistory_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            ChatHistory history = new ChatHistory(this.Key);
            history.Topmost = true;
            history.Show();
        }

        //截图
        private void imgCut_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            this.Hide();
            CaptureImageTool capture = new CaptureImageTool();
            //capture.SelectCursor = new Cursor(Properties.Resources.Arrow_M.Handle);
            if (capture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Drawing.Image image = capture.Image;
                Clipboard.SetDataObject(image);
                this.MyMessageBox.Paste();
            }
            this.Show();
        }





        #region 接收发送文件处理
        private void UDPFileTask()
        {
            if (chatinfo.UserIPAdress != "")
            {
                this.Dispatcher.Invoke(new Action(() =>
              {
                  //监听

                  udpSendFile = new UdpSendFile(chatinfo.UserIPAdress, 10003, 10002);

                  udpSendFile.FileSendBuffer += new FileSendBufferEventHandler(FileSendBuffer);
                  udpSendFile.FileSendAccept += new FileSendEventHandler(FileSendAccept);
                  udpSendFile.FileSendRefuse += new FileSendEventHandler(FileSendRefuse);
                  udpSendFile.FileSendCancel += new FileSendEventHandler(FileSendCancel);
                  udpSendFile.FileSendComplete += new FileSendEventHandler(FileSendComplete);

                  udpSendFile.Start();
              }));
            }
        }
        private void ItemCancelButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item =
                sender as FileTransfersItem;
            SendFileManager sendFileManager =
                       item.Tag as SendFileManager;
            udpSendFile.CancelSend(sendFileManager.MD5);

            SendFileControl.RemoveItem(item);
            ShowFileMsg("取消发送文件:" + sendFileManager.Name);

            HideSendFile();
        }

        private void File_PreviewDragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }

        private void File_PreviewDrop(object sender, DragEventArgs e)
        {
            Array arr = (Array)e.Data.GetData(DataFormats.FileDrop);
            if (arr != null)
            {
                try
                {
                    foreach (var sendfile in arr)
                    {
                        ShowSendFile();
                        SendFileManager sendFileManager = new SendFileManager(
                            sendfile.ToString());
                        if (udpSendFile.CanSend(sendFileManager))
                        {
                            FileTransfersItem item = SendFileControl.AddItem(
                                sendFileManager.MD5,
                                "发送文件",
                                sendFileManager.Name,
                               System.Drawing.Icon.ExtractAssociatedIcon(sendfile.ToString()).ToBitmap(),
                                sendFileManager.Length,
                                FileTransfersItemStyle.Send);
                            item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
                            item.Tag = sendFileManager;
                            sendFileManager.Tag = item;
                            udpSendFile.SendFile(sendFileManager, item.Image);
                        }
                        else
                        {
                            MsgManger.Show("文件正在发送，不能发送重复的文件。");
                        }
                        string strFileMsg = "发送文件：" + sendfile.ToString().Substring(sendfile.ToString().LastIndexOf("\\") + 1);
                        ShowFileMsg(strFileMsg);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        //传送文件
        private void imgSendFile_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    ShowSendFile();
                    SendFileManager sendFileManager = new SendFileManager(
                        ofd.FileName);
                    if (udpSendFile.CanSend(sendFileManager))
                    {
                        FileTransfersItem item = SendFileControl.AddItem(
                            sendFileManager.MD5,
                            "发送文件",
                            sendFileManager.Name,
                           System.Drawing.Icon.ExtractAssociatedIcon(ofd.FileName).ToBitmap(),
                            sendFileManager.Length,
                            FileTransfersItemStyle.Send);
                        item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
                        item.Tag = sendFileManager;
                        sendFileManager.Tag = item;
                        udpSendFile.SendFile(sendFileManager, item.Image);
                        string strFileMsg = "发送文件：" + ofd.FileName.ToString().Substring(ofd.FileName.ToString().LastIndexOf("\\") + 1);
                        ShowFileMsg(strFileMsg);
                    }
                    else
                    {
                        MessageBox.Show("文件正在发送，不能发送重复的文件。");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void FileSendCancel(
            object sender, FileSendEventArgs e)
        {
            FileTransfersItem item =
                e.SendFileManager.Tag as FileTransfersItem;
            if (item != null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    SendFileControl.RemoveItem(item);
                    item.Dispose();
                    ShowFileMsg("对方取消接收文件:" + e.SendFileManager.Name);
                }));
            }
        }

        private void FileSendComplete(
            object sender, FileSendEventArgs e)
        {
            FileTransfersItem item =
                e.SendFileManager.Tag as FileTransfersItem;

            if (item != null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    SendFileControl.RemoveItem(item);
                    item.Dispose();
                    ShowFileMsg("文件:" + e.SendFileManager.Name + "发送完成。");
                    HideSendFile();
                }));
            }
        }

        private void FileSendRefuse(
            object sender, FileSendEventArgs e)
        {
            FileTransfersItem item =
                e.SendFileManager.Tag as FileTransfersItem;
            if (item != null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    SendFileControl.RemoveItem(item);
                    item.Dispose();
                    ShowFileMsg("对方拒绝接收文件:" + e.SendFileManager.Name);
                    HideSendFile();
                }));
            }
        }

        private void FileSendAccept(
            object sender, FileSendEventArgs e)
        {
            FileTransfersItem item =
                e.SendFileManager.Tag as FileTransfersItem;
            if (item != null)
            {
                item.Start();
            }
        }

        private void FileSendBuffer(
            object sender, FileSendBufferEventArgs e)
        {
            FileTransfersItem item =
                e.SendFileManager.Tag as FileTransfersItem;
            if (item != null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    item.TotalTransfersSize += e.Size;
                }));
            }
        }

        public void ShowSendFile()
        {
            this.gridfile.Visibility = Visibility.Visible;

            this.ViewMessgeBox.Margin = new Thickness(24, 85, 250, 193);
            this.MyMessageBox.Margin = new Thickness(24, 0, 250, 44);


            this.gridfile.Width = 240;
        }

        public void HideSendFile()
        {
            if (SendFileControl.Controls.Count == 0)
            {
                this.gridfile.Visibility = Visibility.Collapsed;

                this.ViewMessgeBox.Margin = new Thickness(24, 85, 180, 193);
                this.MyMessageBox.Margin = new Thickness(24, 0, 180, 44);

                this.gridfile.Width = 170;
            }
        }

        public void ShowFileMsg(string strFileMsg)
        {
            //添加信息头
            TextBlock TB = new TextBlock(new Bold(new Run(DateTime.Now.ToString("HH:mm") + "   " + strFileMsg)));
            TB.Foreground = new SolidColorBrush(Colors.Teal);
            BlockUIContainer BU = new BlockUIContainer(TB);
            this.ViewMessgeBox.Document.Blocks.Add(BU);
        }
        #endregion SendFile Events

    }
}